const usersModel = require('../model/usersManage')
const { getComparePwd } = require('../utils/getBcryptPwd')
const { signToken } = require('../utils/token')

// 设置cookie过期时间
const cookieExpires = () => {
  const d = new Date(); // 获取当前时间
  d.setTime(d.getTime() + (24 * 60 * 60 * 1000));
  return d.toGMTString();
};

// 用户登录
const login = async (req, res, next) => {
  res.set('Content-Type', 'application/json; charset=utf-8')
  const { username, password } = req.body
  const user = await usersModel.findOneUser(username)
  if (user) {
    const match = await getComparePwd(password, user.password)
    if (match) {
      // req.session.username = username
      const token = signToken(user)
      // res.set('X-Access-Token', token)
      res.set('Set-Cookie', `sessionId=${token}; path=/; expires=${cookieExpires()}`)
      res.render('success', {
        data: JSON.stringify({})
      })
    } else {
      res.render('error', {
        data: JSON.stringify("用户名或密码错误")
      })
    }
  } else {
    res.render('error', {
      data: JSON.stringify("用户名或密码错误")
    })
  }
}

// 用户信息
const info = async (req, res, next) => {
  res.set('Content-Type', 'application/json; charset=utf-8')
  const { _id } = res.locals.currentUser;
  let user = await usersModel.findUserById(_id)
  if (user) {
    user = {
      roles: ['admin'],
      introduction: 'I am a super administrator',
      avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      name: user.username,
    }
    res.render('success', {
      data: JSON.stringify(user)
    })
  } else {
    res.render('error', {
      data: JSON.stringify("用户名或密码错误")
    })
  }
}

// 用户退出登录
const logout = async (req, res, next) => {
  res.set('Content-Type', 'application/json; charset=utf-8')
  // req.session = null
  res.render('success', {
    data: JSON.stringify({})
  })
}

module.exports = {
  login,
  info,
  logout,
}
